﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;

namespace Code.BLL
{
    public class TakeMoneyManage : ManageBase<TakeMoney>
    {
        /// <summary>
        /// 获取当前用户今天提款的数量
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public int TackMoneyCount_Today(Guid uid)
        {
            var datetime = base.GetServerDate();
            return base.Select(s => s.Where(p => p.UserID == uid)
                .Where(p => p.AddTime.Date == datetime.Value.Date)
                .Count());
        }
        /// <summary>
        /// 添加一条提款记录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public int AddTackMoneyDetail(Guid uid, double money, BankType type, string msg)
        {
            var user = new UserManage().Select(s => s.Where(p => p.ID == uid).Select(p => new { p.Person.BankCardNo, BankName = p.Person.Bank.Name, p.Person.BankCity.Province.ProvinceName, p.Person.BankCity.CityName, p.Person.BankStreet, p.Person.PayAccount }).FirstOrDefault());
            string account = null;
            switch (type)
            {
                case BankType.Bank:
                    account = string.Format("{0}:{1} {2}{5}{3}{4}", user.BankName, user.BankCardNo, user.ProvinceName, user.CityName, user.BankStreet, user.ProvinceName == null ? null : "省");
                    break;
                case BankType.InlinePay:
                    account = user.PayAccount;
                    break;
            }

            NameValue<string, object> insertItem = new NameValue<string, object>()
            {
                {"UserID",uid},
                {"Money",money},
                {"BankType",(short)type},
                {"Account",account},
                {"Remark",msg}
            };
            base.BeginTransaction();
            base.Insert(insertItem);
            NameValue<string, object> update = new NameValue<string, object>()
            {
                {"Balance",new OpteratorValue(Opterator.Subtract,money)},
                {"FreezeMoney",new OpteratorValue(Opterator.Add,money)}
            };
            NameValue<string, object> where = new NameValue<string, object>()
            {
                {"UserID",uid}
            };
            base.Update<Account>(update, where);

            var freezMoneyDetailItem = new NameValue<string,object>
            {
                {"AddTime", DateTime.Now},
                {"FreezeCause", FreezeCause.Freeze_TakeMoney},
                {"State", FreezeMoneyDetailState.Freeze},
                {"Money", money},
                {"UserID", uid}
            };
            base.Insert<FreezeMoneyDetail>(freezMoneyDetailItem);
            return base.ExecuteTransaction(3);
        }

        public IEnumerable<TackMoneys_Mod> GetTackMoneyList(Guid? uid, string where, params object[] parmList)
        {
            IQueryable < TakeMoney > takeMoneys = null;
            if (uid.HasValue)
            {
                takeMoneys = base.Select(s => s.Where(p => p.UserID == uid));
            }
            else
            {
                takeMoneys = base.Select(s => s);
            }
            return takeMoneys.Where(where, parmList)
                .Select(p => 
                    new TackMoneys_Mod {
                        ID=p.ID,
                        User=new User_Comm
                        {
                            Uid=p.UserID,
                            LoginName=p.Users.LoginName,
                            RName=p.Users.Person.Name,
                            CommandID=p.Users.CommandID
                        },
                        Money=p.Money,
                        AddTime=p.AddTime,
                        DoTime=p.DoTime,
                        State=p.State,
                        Remark=p.Remark,
                        Type=(BankType)p.BankType,
                        Account=p.Account,
                    });
        }
        /// <summary>
        /// 获取未处理提款申请的条数
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public int GetTakeMoneyUnDisposeCount(Guid? uid)
        {
            IQueryable < TakeMoney > takeMoneys = null;
            if (uid.HasValue)
            {
                takeMoneys = base.Select(s => s.Where(p => p.UserID == uid));
            }
            else
            {
                takeMoneys = base.Select(s => s);
            }
            return takeMoneys.Where(p => p.State == (short)TakeMoneyState.UnDispose).Count();
        }

        /// <summary>
        /// 处理提款申请
        /// </summary>
        /// <param name="adminID"></param>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public int DisposeTakeMoneyDetail(Guid adminID,long id, TakeMoneyState state, string remark)
        {
            var takeMoney = base.Select(s => s.Where(p => p.ID == id).FirstOrDefault());
            if (takeMoney == null)
                throw new AppException("未找到当前提款详情");
            if (takeMoney.State != (short)TakeMoneyState.UnDispose)
                throw new ValidateException("当前提款申请已处理!");
            if (state != TakeMoneyState.Dispose && state != TakeMoneyState.Refuse)
                throw new AppException("不支持的处理状态");
            var update_takeMoney = new NameValue<string, object>
                {
                    {"State",(short)state},
                    {"AdminID",adminID},
                    {"DoTime",DateTime.Now},
                    {"Remark",new OpteratorValue(Opterator.Add,string.IsNullOrEmpty(remark)?"":"\r\n&&"+remark.Replace("&"," "))}
                };
            var where_takeMoney = new NameValue<string, object>
                {
                    {"ID",id},
                    {"State",(short)TakeMoneyState.UnDispose}
                };
            var freezMoneyDetailItem = new NameValue<string, object>
            {
                {"AddTime", DateTime.Now},
                {"FreezeCause", FreezeCause.Free_Manage},
                {"State", FreezeMoneyDetailState.Free},
                {"Money", takeMoney.Money},
                {"UserID", takeMoney.UserID},
                {"Remark","提款申请"}
            };
            var update_Account = new NameValue<string, object>
            {
                {"FreezeMoney",new OpteratorValue(Opterator.Subtract,takeMoney.Money)}
            };
            var where_Account = new NameValue<string, object>
            {
                {"UserID",takeMoney.UserID}
            };
            if (state == TakeMoneyState.Refuse)
                update_Account.Add("Balance", new OpteratorValue(Opterator.Add, takeMoney.Money));
            if (state == TakeMoneyState.Dispose)
            {
                update_Account.Add("TackMoney", new OpteratorValue(Opterator.Add, takeMoney.Money)); 
            }
            base.BeginTransaction();
            base.Update(update_takeMoney, where_takeMoney);
            base.Insert<FreezeMoneyDetail>(freezMoneyDetailItem);
            base.Update<Account>(update_Account, where_Account);
            var count= base.ExecuteTransaction(3);
            return count;
        }
    }
}
